﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Security.Cryptography;
using System.IO;
using System.Text;

namespace Catering.View_Operaction
{
    public class Bind_Data_to_Controls
    {
        /// <summary>
        /// 绑定ListBox数据，该ListBox用在年份选择上
        /// </summary>
        /// <param name="years"></param>
        public static void BindListBox(List<string> years, ListBox listBox)
        {
            for (int i = 0; i < years.Count; i++)
            {
                ListItem temp = new ListItem(years[i], years[i]);
                listBox.Items.Add(temp);
            }
        }

        /// <summary>
        /// 绑定DropDownList数据，该DropDownList用在年份选择上
        /// </summary>
        /// <param name="years"></param>
        public static void BindListBox(List<string> years, DropDownList ddl)
        {
            for (int i = 0; i < years.Count; i++)
            {
                ListItem temp = new ListItem(years[i], years[i]);
                ddl.Items.Add(temp);
            }
        }

        /// <summary>
        /// 绑定作业区
        /// </summary>
        /// <param name="ddl">要绑定的下拉列表</param>
        /// <param name="listArea">数据</param>
        public static void Bind_Area_ddl(DropDownList ddl, List<Catering_Model.OperationArea> listTemp)
        {
            Catering_Rules.OperationArea oaRules = new Catering_Rules.OperationArea();
            List<Catering_Model.OperationArea> listArea = oaRules.GetAllList(0);
            foreach (Catering_Model.OperationArea item in listArea)
            {
                ListItem temp = new ListItem(item.AreaName, item.id.ToString());
                ddl.Items.Add(temp);
            }
            if (ddl.Items.Count > 0)
            {
                ddl.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// 绑定作业区
        /// </summary>
        /// <param name="ddl">要绑定的下拉列表</param>
        /// <param name="listArea">数据</param>
        public static void Bind_Area_ddl(DropDownList ddl)
        {
            Catering_Rules.OperationArea oaRules = new Catering_Rules.OperationArea();
            List<Catering_Model.OperationArea> listArea = oaRules.GetAllList(0);
            ListItem li = new ListItem("全部", "-10");
            ddl.Items.Add(li);
            foreach (Catering_Model.OperationArea item in listArea)
            {
                ListItem temp = new ListItem(item.AreaName, item.id.ToString());
                ddl.Items.Add(temp);
            }
            if (ddl.Items.Count > 0)
            {
                ddl.SelectedIndex = 0;
            }

        }

        /// <summary>
        /// 绑定作业区
        /// </summary>
        /// <param name="ddl">要绑定的下拉列表</param>
        /// <param name="listArea">数据</param>
        public static void Bind_Area_ddl(DropDownList ddl, bool isAdmin, int areaid, int companyid)
        {
            Bind_Area_ddl(ddl, isAdmin, areaid, companyid, true);
        }

        /// <summary>
        /// 绑定作业区
        /// </summary>
        /// <param name="ddl">要绑定的下拉列表</param>
        /// <param name="listArea">数据</param>
        public static void Bind_Area_ddl(DropDownList ddl, bool isAdmin, int areaid, int companyid, bool isadminalll)
        {
            Bind_Area_ddl(ddl, isAdmin, areaid, companyid, isadminalll, false);
        }

        /// <summary>
        /// 绑定作业区
        /// </summary>
        /// <param name="ddl">要绑定的下拉列表</param>
        /// <param name="listArea">数据</param>
        public static void Bind_Area_ddl(DropDownList ddl, bool isAdmin, int areaid, int companyid, bool isadminalll, bool isziyingcompany)
        {
            if (!isAdmin)
            {
                ddl.Items.Clear();
                Catering_Model.OperationArea area = new Catering_Rules.OperationArea().GetModel(areaid);
                if (area != null)
                {
                    ListItem temp = new ListItem(area.AreaName, area.id.ToString());
                    ddl.Items.Add(temp);
                    ddl.SelectedIndex = 0;
                }
            }
            else
            {
                Catering_Rules.OperationArea oaRules = new Catering_Rules.OperationArea();
                List<Catering_Model.OperationArea> listArea = oaRules.GetAllList(companyid, isziyingcompany);
                if (isadminalll)
                {
                    ListItem li = new ListItem("全部", "-10");
                    ddl.Items.Add(li);
                }
                foreach (Catering_Model.OperationArea item in listArea)
                {
                    ListItem temp = new ListItem(item.AreaName, item.id.ToString());
                    ddl.Items.Add(temp);
                }
                if (ddl.Items.Count > 0)
                {
                    ddl.SelectedIndex = 0;
                }
            }
        }

        /// <summary>
        /// 绑定班组
        /// </summary>
        /// <param name="listItem">选中的作业区ListItem</param>
        /// <param name="listClass">班组数据</param>
        /// <param name="ddl">要绑定的下拉框</param>
        public static void Bind_Class_ddl(ListItem listItem, List<Catering_Model.ClassInfo> listClass, DropDownList ddl)
        {
            if (ddl != null && ddl.Items.Count > 0)
            {
                ddl.Items.Clear();
            }
            if (listItem != null && !string.IsNullOrEmpty(listItem.Value))
            {
                foreach (Catering_Model.ClassInfo item in listClass.Where(c => c.AreaID == Int32.Parse(listItem.Value)))
                {
                    ListItem temp = new ListItem(item.CName, item.id.ToString());
                    ddl.Items.Add(temp);
                }
                if (ddl.Items.Count > 0)
                {
                    ddl.SelectedIndex = 0;
                }
            }
        }

        /// <summary>
        /// 绑定班组
        /// </summary>
        /// <param name="listItem">选中的作业区ListItem</param>
        /// <param name="listClass">班组数据</param>
        /// <param name="ddl">要绑定的下拉框</param>
        public static void Bind_Class_ddl(ListItem listItem, DropDownList ddl)
        {
            Catering_Rules.ClassInfo classRules = new Catering_Rules.ClassInfo();
            List<Catering_Model.ClassInfo> listClass = classRules.GetAllList(0);
            if (ddl != null && ddl.Items.Count > 0)
            {
                ddl.Items.Clear();
            }
            ListItem li = new ListItem("全部", "-10");
            ddl.Items.Add(li);
            if (listItem != null && !string.IsNullOrEmpty(listItem.Value))
            {

                foreach (Catering_Model.ClassInfo item in listClass.Where(c => c.AreaID == Int32.Parse(listItem.Value)))
                {
                    ListItem temp = new ListItem(item.CName, item.id.ToString());
                    ddl.Items.Add(temp);
                }
                if (ddl.Items.Count > 0)
                {
                    ddl.SelectedIndex = 0;
                }
            }
        }

        /// <summary>
        /// 绑定班组
        /// </summary>
        /// <param name="listItem">选中的作业区ListItem</param>
        /// <param name="listClass">班组数据</param>
        /// <param name="ddl">要绑定的下拉框</param>
        public static void Bind_Class_ddl(ListItem listItem, DropDownList ddl, bool isAdmin, int classid)
        {
            Bind_Class_ddl(listItem, ddl, isAdmin, classid, true);
        }

        /// <summary>
        /// 绑定班组
        /// </summary>
        /// <param name="listItem">选中的作业区ListItem</param>
        /// <param name="listClass">班组数据</param>
        /// <param name="ddl">要绑定的下拉框</param>
        public static void Bind_Class_ddl(ListItem listItem, DropDownList ddl, bool isAdmin, int classid, bool isadminalll)
        {
            if (isAdmin)
            {
                Catering_Rules.ClassInfo classRules = new Catering_Rules.ClassInfo();
                List<Catering_Model.ClassInfo> listClass = classRules.GetAllList(0);
                if (ddl != null && ddl.Items.Count > 0)
                {
                    ddl.Items.Clear();
                }
                if (isadminalll)
                {
                    ListItem li = new ListItem("全部", "-10");
                    ddl.Items.Add(li);
                }
                if (listItem != null && !string.IsNullOrEmpty(listItem.Value))
                {

                    foreach (Catering_Model.ClassInfo item in listClass.Where(c => c.AreaID == Int32.Parse(listItem.Value)))
                    {
                        ListItem temp = new ListItem(item.CName, item.id.ToString());
                        ddl.Items.Add(temp);
                    }
                    if (ddl.Items.Count > 0)
                    {
                        ddl.SelectedIndex = 0;
                    }
                }
            }
            else
            {
                ddl.Items.Clear();
                Catering_Model.ClassInfo classmodel = new Catering_Rules.ClassInfo().GetModel(classid);
                if (classmodel != null)
                {
                    ListItem temp = new ListItem(classmodel.CName, classmodel.id.ToString());
                    ddl.Items.Add(temp);
                    ddl.SelectedIndex = 0;
                }
            }
        }

        /// <summary>
        /// 绑定作业区，包含自营公司
        /// </summary>
        /// <param name="ddl"></param>
        public static void Bind_DDL_Area(DropDownList ddl)
        {
            Catering_Rules.OperationArea oaRules = new Catering_Rules.OperationArea();
            List<Catering_Model.OperationArea> listArea = oaRules.GetAllList(0);
            //ListItem temp1 = new ListItem("自营公司", "-10");
            //ddl.Items.Add(temp1);
            foreach (Catering_Model.OperationArea item in listArea)
            {
                ListItem temp = new ListItem(item.AreaName, item.id.ToString());
                ddl.Items.Add(temp);
            }
            if (ddl.Items.Count > 0)
            {
                ddl.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// 为dt添加 tempid 序号
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static DataTable AddTempIdToDataTable(DataTable dt)
        {
            dt.Columns.Add(new DataColumn("tempid"));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i]["tempid"] = i + 1;
            }
            return dt;
        }

        public static void Bind_Tree_OreaAndCalss(TreeView tv,int companyid)
        {
            if (tv != null && tv.Nodes.Count > 0)
            {
                tv.Nodes.Clear();
            }
            Catering_Rules.OperationArea oaRules = new Catering_Rules.OperationArea();
            List<Catering_Model.OperationArea> listArea = oaRules.GetModelList(" temp2=" + companyid + " ");
            Catering_Rules.ClassInfo classRules = new Catering_Rules.ClassInfo();
            List<Catering_Model.ClassInfo> listClass = classRules.GetAllList(0);
            foreach (var itemArea in listArea)
            {
                TreeNode tempArea = new TreeNode(itemArea.AreaName, itemArea.id.ToString());
                tempArea.Target = "zyq";
                foreach (var itemClass in listClass.Where(p => p.AreaID == itemArea.id))
                {
                    TreeNode tempClass = new TreeNode(itemClass.CName, itemClass.id.ToString());
                    tempClass.Target = "bz";
                    tempArea.ChildNodes.Add(tempClass);
                }
                tv.Nodes.Add(tempArea);
            }
            tv.DataBind();
        }

        /// <summary>
        /// 绑定短信接收人
        /// </summary>
        public static void Bind_Tree_Receiver(TreeView tv, string pid, bool isziyingcompany)
        {
            #region 旧

            //List<Catering_Model.ClassInfo> listClass = new Catering_Rules.ClassInfo().GetModelList("");
            //Catering_Rules.ContactsBLL contracts = new Catering_Rules.ContactsBLL();
            //DataTable dtContract = contracts.GetContactsForArea("-10");
            //Catering_Rules.OperationArea oArea = new Catering_Rules.OperationArea();
            //List<Catering_Model.OperationArea> ListArea = oArea.GetModelList("");
            //foreach (var itemArea in ListArea)
            //{
            //    TreeNode temp1 = new TreeNode(itemArea.AreaName, itemArea.id.ToString());
            //    foreach (var item in listClass.Where(p => p.AreaID == Convert.ToInt32(temp1.Value)))
            //    {
            //        TreeNode temp2 = new TreeNode(item.CName, item.id.ToString());
            //        for (int ii = 0; ii < dtContract.Rows.Count; ii++)
            //        {
            //            if (Convert.ToInt32(dtContract.Rows[ii]["classId"]) == item.id)
            //            {
            //                TreeNode temp3 = new TreeNode(dtContract.Rows[ii]["name"].ToString(), dtContract.Rows[ii]["id"].ToString());
            //                temp2.ShowCheckBox = true;
            //                temp3.ShowCheckBox = true;
            //                temp2.ChildNodes.Add(temp3);
            //            }
            //        }
            //        temp1.ChildNodes.Add(temp2);
            //    }

            //    if (temp1 != null)
            //    {
            //        tv.Nodes.Add(temp1);
            //    }
            //}

            #endregion
            string strarealist = new Catering_Rules.OperationArea().GetStrAreaIDListByPersonnelID(pid);
            string areawhere = "";
            if (!string.IsNullOrEmpty(strarealist))
            {
                areawhere = string.Format(" ID IN ({0}) ", strarealist);
            }
            List<Catering_Model.E_Personnel> listPerson = new Catering_Rules.T_Personnel().GetModelList("");
            List<Catering_Model.OperationArea> ListArea = new Catering_Rules.OperationArea().GetModelList(areawhere, isziyingcompany);
            List<Catering_Model.ClassInfo> listClass = new Catering_Rules.ClassInfo().GetModelList("");
            foreach (Catering_Model.OperationArea area in ListArea)
            {
                TreeNode temp1 = new TreeNode(area.AreaName, area.id.ToString());
                //temp1.ImageUrl = "~/Images/WebResource.gif";
                foreach (Catering_Model.ClassInfo classinfo in listClass.Where(p => p.AreaID == area.id))
                {
                    TreeNode temp2 = new TreeNode(classinfo.CName, classinfo.id.ToString());
                    //temp2.ImageUrl = "~/Images/person.gif";
                    int tempi = 0;
                    foreach (Catering_Model.E_Personnel person in listPerson.Where(p => p.ClassID == classinfo.id))
                    {
                        if (person.PID == 13 || person.PID == 11 || person.ClassID == 50)//管事或者作业区经理或者自营公司人员
                        {
                            int WorkingState = new Catering_Rules.AttendanceRecord().GetPersonnelStateByPersonnelID(person.id, DateTime.Now.AddDays(-1));
                            if (!string.IsNullOrEmpty(person.Tel))
                            {
                                TreeNode temp3 = new TreeNode();
                                if (WorkingState == 1)
                                {
                                    temp3.Text = "<span class='Red'>" + person.Name + "</span>(" + person.Tel + ")";
                                }
                                else
                                {
                                    temp3.Text = person.Name + "(" + person.Tel + ")";
                                }
                                //temp3.ImageUrl = "~/Images/WebResource1.gif";
                                temp3.Value = person.id.ToString();
                                temp2.ShowCheckBox = true;
                                temp3.ShowCheckBox = true;
                                temp2.ChildNodes.Add(temp3);
                            }
                            else
                            {
                                TreeNode temp3 = new TreeNode();
                                if (WorkingState == 1)
                                {
                                    temp3.Text = "<span class='Red'>" + person.Name + "</span>";
                                }
                                else
                                {
                                    temp3.Text = person.Name;
                                }
                                temp3.Value = person.id.ToString();
                                temp2.ChildNodes.Add(temp3);
                            }
                            if (person.ClassID != 50 && tempi > 0) break;
                            tempi++;
                        }
                    }
                    temp1.ChildNodes.Add(temp2);
                }
                tv.Nodes.Add(temp1);
            }
        }

        public static void Bing_Personnel_To_TreeView(TreeView tv, string pid, bool isziyingcompany)
        {
            //List<Catering_Model.Personnel> listPerson = new Catering_Rules.Personnel().GetModelList("");
            string strarealist = new Catering_Rules.OperationArea().GetStrAreaIDListByPersonnelID(pid);
            string areawhere = "";
            if (!string.IsNullOrEmpty(strarealist))
            {
                areawhere = string.Format(" ID IN ({0}) ", strarealist);
            }
            List<Catering_Model.OperationArea> ListArea = new Catering_Rules.OperationArea().GetModelList(areawhere, isziyingcompany);
            List<Catering_Model.ClassInfo> listClass = new Catering_Rules.ClassInfo().GetModelList("");
            foreach (Catering_Model.OperationArea area in ListArea)
            {
                TreeNode temp1 = new TreeNode(area.AreaName, area.id.ToString());
                temp1.ImageUrl = "~/Images/WebResource.gif";
                foreach (Catering_Model.ClassInfo classinfo in listClass.Where(p => p.AreaID == area.id))
                {
                    TreeNode temp2 = new TreeNode(classinfo.CName, classinfo.id.ToString());
                    temp2.ImageUrl = "~/Images/person.gif";
                    temp2.ShowCheckBox = true;
                    //foreach (Catering_Model.Personnel person in listPerson.Where(p => p.ClassID == classinfo.id))
                    //{
                    //    TreeNode temp3 = new TreeNode(person.Name, person.id.ToString());
                    //    temp3.ImageUrl = "~/Images/WebResource1.gif";
                    //    temp2.ShowCheckBox = true;
                    //    temp3.ShowCheckBox = true;
                    //    temp2.ChildNodes.Add(temp3);
                    //}
                    temp1.ChildNodes.Add(temp2);
                }
                tv.Nodes.Add(temp1);
            }
        }

        public static void Bind_Material_cbo(List<Catering_Model.E_RawMaterials> listInfo, CheckBoxList cboList)
        {
            if (cboList != null && cboList.Items.Count > 0)
            {
                cboList.Items.Clear();
            }
            cboList.Items.Add(new ListItem("全部", "-1"));
            foreach (var item in listInfo)
            {
                ListItem temp = new ListItem();
                temp.Text = item.TypeName;
                temp.Value = item.id.ToString();
                cboList.Items.Add(temp);
            }
        }

        public static string Bind_ReportTitle(string AREAID, string CLASSID, DateTime DTIME, string LASTSTR)
        {
            return Bind_ReportTitle(AREAID, CLASSID, DTIME, DateTime.Now, false, LASTSTR, false);
        }

        public static string Bind_ReportTitle(string AREAID, string CLASSID, DateTime DTIME, DateTime DTIMEEND, bool ISENDTIME, string LASTSTR, bool FlagDay)
        {
            if (FlagDay)
            {
                string Title = DTIME.Year + "年";
                Title += DTIME.Month + "月";
                Title += DTIME.Day + "日";
                if (ISENDTIME)
                {
                    Title += "到" + DTIME.Year + "年" + DTIMEEND.Month + "月" + DTIMEEND.Day + "日";
                }
                Catering_Model.OperationArea OAreaInfo = new Catering_Rules.OperationArea().GetModel(Convert.ToInt32(AREAID));
                Catering_Model.ClassInfo ClassInfo = new Catering_Rules.ClassInfo().GetModel(Convert.ToInt32(CLASSID));
                if (OAreaInfo != null && !string.IsNullOrEmpty(OAreaInfo.AreaName))
                {
                    Title += OAreaInfo.AreaName;
                    if (ClassInfo != null && !string.IsNullOrEmpty(ClassInfo.CName))
                    {
                        Title += ClassInfo.CName + "班组";
                    }
                }
                Title += LASTSTR;
                return Title;
            }
            else
            {
                string Title = DTIME.Year + "年";
                if (!DTIME.Second.Equals(11))
                {
                    Title += DTIME.Month + "月";
                }
                if (ISENDTIME)
                {
                    Title += "到" + DTIME.Year + "年" + DTIMEEND.Month + "月";
                }
                Catering_Model.OperationArea OAreaInfo = new Catering_Rules.OperationArea().GetModel(Convert.ToInt32(AREAID));
                Catering_Model.ClassInfo ClassInfo = new Catering_Rules.ClassInfo().GetModel(Convert.ToInt32(CLASSID));
                if (OAreaInfo != null && !string.IsNullOrEmpty(OAreaInfo.AreaName))
                {
                    Title += OAreaInfo.AreaName;
                    if (ClassInfo != null && !string.IsNullOrEmpty(ClassInfo.CName))
                    {
                        Title += ClassInfo.CName + "班组";
                    }
                }
                Title += LASTSTR;
                return Title;
            }
        }

        public static string MessageAlert(string mes)
        {
            string str = @"<script>alert('";
            str += mes;
            str += @"')</script>";
            return str;
        }

        /// <summary>
        /// 获取用户所在的公司，作业区和班组
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="companyid"></param>
        /// <param name="gorupid"></param>
        /// <param name="classid"></param>
        public static void GetCompanyByCurrentUser(string userid, out int companyid, out int gorupid, out int classid, out bool isAdmin)
        {
            int quanzhong = 1;
            GetCompanyByCurrentUser(userid, out companyid, out gorupid, out classid, out isAdmin, out quanzhong);
        }

        /// <summary>
        /// 获取用户所在的公司，作业区和班组
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="companyid"></param>
        /// <param name="gorupid"></param>
        /// <param name="classid"></param>
        public static void GetCompanyByCurrentUser(string userid, out int companyid, out int gorupid, out int classid, out bool isAdmin, out int quanzhong)
        {
            int id = 0;
            companyid = 0;
            gorupid = 0;
            classid = 0;
            isAdmin = false;
            quanzhong = 1;
            Int32.TryParse(userid, out id);
            if (id <= 0) return;
            Catering_Model.user userInfo = new Catering_Rules.user().GetModel(id);
            if (userInfo == null) return;
            id = userInfo.URole == null ? 0 : (int)userInfo.URole;
            Catering_Model.Role role = new Catering_Rules.Role().GetModel(id);
            if (role == null) return;
            isAdmin = role.temp1 > 5 ? true : false;
            quanzhong = role.temp1;
            id = userInfo.PersonnelID == null ? 0 : (int)userInfo.PersonnelID;
            if (id <= 0) return;
            Catering_Model.E_Personnel person = new Catering_Rules.T_Personnel().GetModel(id);
            if (person == null) return;
            classid = person.ClassID == null ? 0 : person.ClassID;
            if (classid <= 0) return;
            DataTable dt = new Catering_Rules.Company().GetView_CompanyClass(classid.ToString()).Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                if (!(dt.Rows[0]["CompanyID"] is DBNull)) companyid = Convert.ToInt32(dt.Rows[0]["CompanyID"]);
                if (!(dt.Rows[0]["AreaID"] is DBNull)) gorupid = Convert.ToInt32(dt.Rows[0]["AreaID"]);
            }
            dt.Dispose();
        }

        const string KEY_64 = "beijitzA";//注意了，是8个字符，64位
        const string IV_64 = "beijitzA";
        /// <summary>
        /// MD5逆解密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Decode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);
            }
            catch
            {
                return null;
            }

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
        }

        /// <summary>
        /// MDB可逆加密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Encode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(cst);
            sw.Write(data);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);

        }
    }
}